<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    show-footer
    default-fullscreen
    @ok="handleSubmit"
  >
    <template #title>
      编辑
    </template>
    <template #footer>
      <a-button @click="closeModal" :loading="btnLoading">取消</a-button>
      <a-button
        type="primary"
        @click="handleSubmit()"
        :loading="btnLoading"
        >保存</a-button
      >                                     
    </template>
    <a-button type="primary" @click="handleAddTimeRange">添加时段</a-button>
    <Form ref="form" :label-col="{ span: 6 }" :model="formModel">
      <Row :key="index" v-for="(item, index) in formModel.timeRanges">
        <Col :span="6">
          <FormItem label="开始时间" :name="['timeRanges', index, 'startTime']" :rules="{ required: true, message: '请输入开始时间', trigger: 'blur' }">
            <TimePicker v-model:value="item.startTime" disabled class="w-full" :format="'HH:mm'" :value-format="'HH:mm'"/>
          </FormItem>
        </Col>
        <Col :span="6">
          <FormItem label="结束时间" :name="['timeRanges', index, 'endTime']" :rules="{ required: true, message: '请输入结束时间', trigger: 'blur' }">
            <TimePicker v-model:value="item.endTime" :disabled = "formModel.timeRanges[index + 1]" :disabledTime="(now: Dayjs) => disabledStart(index, now, 'end')" class="w-full" :format="'HH:mm'" :value-format="'HH:mm'" />
          </FormItem>
        </Col>
        <Col :span="6">
          <FormItem label="服务费" :name="['timeRanges', index,'serviceUnitPrice']" :rules="{ required: true, message: '请输入服务费', trigger: 'blur' }">
            <InputNumber v-model:value="item.serviceUnitPrice" :precision="4"/>
          </FormItem>
        </Col>
        <Col :span="6">
          <FormItem label="原服务费" :name="['timeRanges', index,'serviceUnitPriceBefore']" :rules="{ required: true, message: '请输入原服务费', trigger: 'blur' }">
            <InputNumber v-model:value="item.serviceUnitPriceBefore" :precision="4"/>
          </FormItem>
        </Col>
        <Col :span="6">
          <FormItem label="电费" :name="['timeRanges', index, 'powerUnitPrice']" :rules="{ required: true, message: '请输入电费', trigger: 'blur' }">
            <InputNumber v-model:value="item.powerUnitPrice" :precision="4"/>
          </FormItem>
        </Col>
        <Col :span="6">
          <FormItem label="原电费" :name="['timeRanges', index, 'powerUnitPriceBefore']" :rules="{ required: true, message: '请输入原电费', trigger: 'blur' }">
            <InputNumber v-model:value="item.powerUnitPriceBefore" :precision="4"/>
          </FormItem>
        </Col>
        <Col :span="6">
          <FormItem label="停车费" :name="[ 'timeRanges', index, 'parkUnitPrice' ]" :rules="{ required: true, message: '请输入停车费', trigger: 'blur' }">
            <InputNumber v-model:value="item.parkUnitPrice" :precision="4"/>
          </FormItem>
        </Col>
        <Col :span="6">
          <FormItem label="原停车费" :name="[ 'timeRanges', index, 'parkUnitPriceBefore' ]" :rules="{ required: true, message: '请输入原停车费', trigger: 'blur' }">
            <InputNumber v-model:value="item.parkUnitPriceBefore" :precision="4"/>
          </FormItem>
        </Col>
        <Col :span="6">
          <FormItem label="类型" :name="[ 'timeRanges', index, 'type' ]" :rules="{ required: true, message: '请选择类型', trigger: 'change' }">
            <RadioGroup v-model:value="item.type" :options="[
              {
                label: '峰时', value: '0'
              },{
                label: '平时', value: '1'
              },{
                label: '谷时', value: '2'
              },{
                label: '尖峰时', value: '3'
              }
            ]" />
          </FormItem>
        </Col>
      </Row>
    </Form>
    <Row>
        <Form :model="stationModel">        
          <FormItem label="可使用电站">
            <CheckboxGroup v-model:value="stationModel.stationIds" :options="stationList" />
          </FormItem>
        </Form>
      </Row>
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { BasicModal, useModalInner } from '@/components/Modal';
import { Form, FormItem, TimePicker, InputNumber, RadioGroup, CheckboxGroup, Row, Col } from 'ant-design-vue';
import { useMessage } from '@/hooks/web/useMessage';
import { useThrottleFn } from '@vueuse/core';
import { defHttp } from '@/utils/http/axios';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
const emit = defineEmits(['success', 'register']);
const btnLoading = ref(false);
const { createMessage } = useMessage();
type RangeItem = {
  startTime: string;
  endTime: string;
  serviceUnitPrice: number;
  serviceUnitPriceBefore: number;
  powerUnitPrice: number;
  powerUnitPriceBefore: number;
  parkUnitPrice: number;
  parkUnitPriceBefore: number;
  type: string[];
};
const form = ref<any>();
const stationModel = reactive({
  stationIds: []
})
const standardId = ref('');
const getRangeItemList = async () => {
  const res = await defHttp.get({ url: `/admin/main/chargeStandardItemList/${standardId.value}` });
  formModel.timeRanges = res;
}
const getStationList = async () => {
  const res = await defHttp.get({ url: `/admin/main/stationListByType/1` });
  debugger
  stationModel.stationIds = res.filter(item => item.mpChargeStandardId == standardId.value).map(item => item.id);
  stationList.value = res.map(item => {
    return {
      label: item.name,
      value: item.id
    }
  })  
}
const disabledStart = (index, now, type) => {
    return {
      disabledHours: () => {
        // 第一组区间 开始只能选00:00 
        // 结束只能选00:00之后的时间
        if (index == 0) {
          if (type == 'end') {
            return []
          }
        } else {
          if (type == 'end') {
            const preStartTime = formModel.timeRanges[index].startTime;
            const preStartTimeHourse = preStartTime.split(':')[0];
            const preStartTimeMinute = preStartTime.split(':')[1];
            return Array.from({ length: 24 }, (_, i) => {
              // 如果上一组结束时间分钟数是59
              if (parseInt(preStartTimeMinute) == 59) {
                if (i <= parseInt(preStartTimeHourse)) return i;
              } else {
                // 非59分钟结束时间 则不禁用上一组结束时间的小时数
                if (i < parseInt(preStartTimeHourse)) {
                  return i;
                }
              }
            });
          }
        }
      },
      disabledMinutes: (selectHours: number) => {
        if (index == 0) {
          if (type == 'end') {
            if (selectHours == 0) {
              return [0]
            } else {
              return []
            }
          }
        } else {
          if (type =='end') {
            const preStratTime = formModel.timeRanges[index].startTime;
            const preStratTimeHourse = preStratTime.split(':')[0];
            const preStratTimeMinute = preStratTime.split(':')[1];
            if (parseInt(preStratTimeHourse) == selectHours) {
              return Array.from({ length: 60 }, (_, i) => {
                if (i <= parseInt(preStratTimeMinute)) {
                  return i;
                }
              });
            }
          }
        }
      }
    }
}
const formModel = reactive({
  timeRanges: [] as RangeItem[],
});
const stationList = ref<any[]>([]);
const [registerModal, { closeModal, changeLoading }] =
useModalInner(async (data) => {
  standardId.value = data.id;
  changeLoading(true);
  try {
    await getRangeItemList();
    await getStationList();
  } finally {
    changeLoading(false);
  }
});
const handleSubmit = useThrottleFn(doSubmit, 1000);
async function doSubmit() {
  try {
    const ranges = formModel.timeRanges;
    if (ranges.length == 0) {
      createMessage.error('请至少添加一组时段');
      return;
    }
    if (ranges[ranges.length - 1].endTime != '23:59') {
      createMessage.error('最后一组时段结束时间必须为23:59');
      return;
    }
    changeLoading(true);
    btnLoading.value = true;
    const res = await defHttp.post({ url: '/chargeStandard/ChargeStandard/save', params: { id: standardId.value, stationId: stationModel.stationIds, chargeDetailList: formModel.timeRanges } });
    createMessage.success(res);
    emit('success');
    closeModal();
  } finally {
    btnLoading.value = false;
    changeLoading(false);
  }
}

const handleAddTimeRange = () => {
  form.value.validate().then((res) => {
    const addData: RangeItem = {
      startTime: formModel.timeRanges.length == 0 ? "00:00" : dayjs(formModel.timeRanges[formModel.timeRanges.length - 1].endTime, 'HH:mm').add(1, 'minute').format('HH:mm'),
      endTime: '',
      serviceUnitPrice: 0,
      serviceUnitPriceBefore: 0,
      powerUnitPrice: 0,
      powerUnitPriceBefore: 0,
      parkUnitPrice: 0,
      parkUnitPriceBefore: 0,
      type: [],
    }
    formModel.timeRanges.push(addData)
  })
  
}
</script>
